package com.jiuqi.captcha.controller;

import com.jiuqi.captcha.utils.CaptchaUtil;
import com.jiuqi.captcha.utils.R;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.Base64;

@Controller
public class CaptchaController {
    @GetMapping("/")
    public String index(HttpSession session, Model model) throws IOException {
        byte[] captchaImageBytes = CaptchaUtil.generateCaptchaImage(session);
        String captchaImageBase64String = Base64.getEncoder().encodeToString(captchaImageBytes);
        String captchaText = session.getAttribute("captchaText").toString();
        model.addAttribute("captchaImage", captchaImageBase64String);
        model.addAttribute("captchaText", captchaText);
        return "index";
    }

    @GetMapping("/getCaptcha")
    @ResponseBody
    public R getCaptcha(HttpSession session) throws IOException {
        byte[] captchaImageBytes = CaptchaUtil.generateCaptchaImage(session);
        System.out.println(captchaImageBytes);
        String captchaText = session.getAttribute("captchaText").toString();
        return R.ok().put("captchaImageBytes", captchaImageBytes).put("captchaText", captchaText);
    }
}
